﻿namespace EyeOpen.Dependency
{
    using System;
    using System.Configuration;
    using System.Reflection;

    internal class DependencyContainerFactory
    {
        private const string DependencyServiceType = "DependencyContainerType";

        public IDependencyContainer CreateDependencyContainer()
        {   
            return BuildContainer();
        }

        private IDependencyContainer BuildContainer()
        {
            var dependencyContainerName = ConfigurationManager.AppSettings[DependencyServiceType];

            if (string.IsNullOrEmpty(dependencyContainerName))
            {
                throw new ArgumentException(@"Must define the key ""DependencyServiceType"" in the configuration file and a valid class that implements ""IDependencyContainer"".");
            }

            var typeTokens = dependencyContainerName.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            var assemblyName = typeTokens[1].Trim();
            var dependencyContainerTypeName = typeTokens[0].Trim();

            var dependencyContainerType = Assembly.Load(assemblyName).GetType(dependencyContainerTypeName);            

            var dependencyContainer = (IDependencyContainer)Activator.CreateInstance(dependencyContainerType);

            return dependencyContainer;
        }
    }                                                                                                   
}